package com.wondersgroup.fjzlpt.tbxt.config;

import com.quick.framework.boot.web.filter.CertAfterZuulFilter;
import com.quick.framework.boot.web.filter.NoneFilter;
import com.wondersgroup.fjzlpt.tbxt.feign.CertFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by lion on 2017/6/16.
 */
@Configuration
@ConfigurationProperties(prefix="common")
public class FilterConfig {

    /**跳转的URL*/
    @Value("${common.loginUrl}")
    private String loginUrl;
    @Value("${common.domainKey}")
    private String domainKey;

    List<String> certParrent = new ArrayList<>();

    List<String> ignoreParrent = new ArrayList<>();

    @Autowired
    CertFeignService certService;

    @Bean(name = "SecurityFilterChain")
    public Filter getFilterChainProxy() {
        List<SecurityFilterChain> filterChains = new ArrayList<SecurityFilterChain>();

        Filter noneFilter = new NoneFilter();
        addChain(filterChains, this.ignoreParrent, noneFilter);

        Filter CertAfterZuulFilter = new CertAfterZuulFilter(certService, domainKey);
        addChain(filterChains, this.certParrent, CertAfterZuulFilter);

        FilterChainProxy filterChainProxy = new FilterChainProxy(filterChains);
        return filterChainProxy;
    }

    private void addChain(List<SecurityFilterChain> filterChains, List<String> list, Filter... filters){
        if(list != null){
            Iterator<String> iter = list.iterator();
            while(iter.hasNext()){
                String parrent = iter.next();
                AntPathRequestMatcher matcher = new AntPathRequestMatcher(parrent);
                SecurityFilterChain chain = new DefaultSecurityFilterChain(matcher, filters);
                filterChains.add(chain);
            }
        }
    }

    public List<String> getCertParrent() {
        return certParrent;
    }

    public void setCertParrent(List<String> certParrent) {
        this.certParrent = certParrent;
    }

    public List<String> getIgnoreParrent() {
        return ignoreParrent;
    }

    public void setIgnoreParrent(List<String> ignoreParrent) {
        this.ignoreParrent = ignoreParrent;
    }
}
